/**
 * @author 陈泰来
 * @version V1.0
 * @Project echo-java-base
 * @Title 文件枚举任务
 * @Description *
 * @Package concurrent.blockingQueue
 * @date 2021/3/19 5:01 下午
 * @Copyright:学如逆水行舟，不进则退 .
 */
package concurrent.blockingQueue.filesearch;

import java.io.File;
import java.util.concurrent.BlockingQueue;

public class FileEnumerationTask implements Runnable {

    private final BlockingQueue<File> queue;

    private final File startingDirectory;

    public static File DUMMY = new File("");

    public FileEnumerationTask(BlockingQueue<File> queue, File startingDirectory) {
        this.queue = queue;
        this.startingDirectory = startingDirectory;
    }

    @Override
    public void run() {
        try {
            //深度遍历 put文件
            enumerate(startingDirectory);
            //put最后一个空文件作为结束标记
            queue.put(DUMMY);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void enumerate(File directory) throws InterruptedException {
        File[] files = directory.listFiles();

        for (File file : files) {
            //是文件夹则递归搜索
            if (file.isDirectory()) enumerate(file);
            else {
                queue.put(file);
//                System.out.printf("[file_enumeration] 文件: %s 已被加载到阻塞队列  \n", file.getName());
            }
        }
    }

}
